import 'dart:io';

import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_router/src/router.dart';
import 'package:xsdk_flutter/xsdk/operation/x_constant_temp.dart';
import 'package:xsdk_flutter/xsdk/utils/webserver/support/x_restful_api_router.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_date.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_file.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_log.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_response.dart';


/*
RESTFul风格,具有一组相同url前缀的api, demo手动定义路由

上传文件
https://pub-web.flutter-io.cn/packages/shelf_multipart/install

dependencies:
  shelf_multipart: ^1.0.0

import 'package:shelf_multipart/form_data.dart';
import 'package:shelf_multipart/multipart.dart';


 */
class XDemoRESTFulApiRouter_upload extends XRESTFulApiRouter{
  XDemoRESTFulApiRouter_upload():super(urlPrefixPath: '/upload');

  /*
  上传图片
  一般web后台都会把文件资源存储在另外一个文件服务器中,这里flutter小型服务也支持简单的文件上传功能,
  参数一般为form表单,当解析到request为isMultipart时,则对文件流进行读取,并写到本地路径中
  注意: 由于dart是单线程,写文件是耗时io操作,必须使用IOSink+stream方式写入,否则内存会拉满导致应用崩溃
   */
  Future<Response> _handler_uploadPhoto(Request request) async {


    // if (request.multipart() case var multipart?) {
    if (false) {
      // final description = StringBuffer('Parsed form multipart request\n');
      // await for (final formData in request.multipartFormData) {
      //   description
      //       .writeln('${formData.name}: ${await formData.part.readString()}');
      // }
      // return Response.ok(description.toString());

      //初始化文件夹
      String uploadPath='${XTempData.appDocumentsDirectoryPath}/uploadPhoto';
      await XFileUtils.initFolderPath(uploadPath);

      //上传成功的文件路径
      List<String> uploadSuccessFilePaths=[];


      // await for (final part in multipart.parts) {
      //   //实测formData.filename = null
      //   XLogUtils.printLog('---formData,key=${part.headers}');
      //
      //   final headers = part.headers;
      //   // part implements the `Stream<List<int>>` interface which can be used to
      //   // read data. You can also use `part.readBytes()` or `part.readString()`
      //
      //   // //保存文件
      //   // if(formData.name.startsWith('file')){
      //   //   String fileName='photo_${XDateUtils.getCurrentTime_ms()}.jpg';
      //   //   String filePath='$uploadPath/$fileName';
      //   //   File file=File(filePath);
      //   //
      //   //   IOSink ioSink=file.openWrite();
      //   //   await ioSink.addStream(formData.part);
      //   //   await ioSink.flush();
      //   //   await ioSink.close();
      //   //
      //   //   uploadSuccessFilePaths.add(fileName);
      //   //
      //   // }
      //
      // }

      //实测遍历request.parts报错
      // await for (final part in request.parts) {
      //   XLogUtils.printLog('---part=${part.toString()}, headers=${part.headers}');
      //   // part.readBytes()
      //   // part.readString()
      // }

      String response=XResponseUtils.responseBodyJson(
          code: XResponseUtils.SuccessCode,
          message: 'ok',
          data: uploadSuccessFilePaths,
      );

      return Response.ok(response);


    }
    // else if(request.formData() case var form?){
    //   // Read all form-data parameters into a single map:
    //   final parameters = <String, String>{
    //     await for (final formData in form.formData)
    //       formData.name: await formData.part.readString(),
    //   };
    //
    //   String response=XResponseUtils.responseBodyJson(
    //     code: XResponseUtils.SuccessCode,
    //     message: 'ok',
    //   );
    //   return Response.ok(response);
    //
    // }
    else {

      String response=XResponseUtils.responseBodyJson(code: '-1', message: 'Not a multipart request');
      return Response.ok(response);
    }
  }

  //重写手动定义路由
  @override
  void initRouter(Router router) {
    //上传图片 访问:http://192.168.1.254:8080/upload/photo
    router.post('/photo', _handler_uploadPhoto);
  }

}